<?php

namespace posts\model;

require_once("posts/model/Post.php");

class PostDAL {

	private static $usersTable = "users";
	private static $postsTable = "posts";
	private $mysqli;

 	public function __construct(\common\model\BaseDAL $baseDAL) {
        //initiate and connect to mysqli database
 		$this->mysqli = $baseDAL->mysqli;
 		
 	}

 	/**	
     * Returns an array of posts from the database
     * @return array users
     */
    public function getAllPosts() {
        $posts = array();
        $sql = "SELECT users.username, posts.postTitle, posts.pk, posts.postText, posts.image
        		FROM ".self::$usersTable."
        		INNER JOIN ".self::$postsTable." ON users.pk = posts.ownerId;";

        $statement = $this->mysqli->prepare($sql);
        if ($statement === false) {
            throw new \Exception("Preparation of $sql statement failed");
        }
        if ($statement->execute() === false) {
            throw new \Exception("Execution of $sql statement failed");
        }
        $result = $statement->get_result();
        while ($object = $result->fetch_array(MYSQLI_ASSOC))
        {
            $posts[] = new \posts\model\Post($object["username"], 
                                             $object["pk"], 
                                             $object["postTitle"], 
                                             $object["postText"],
                                             $object["image"]);
        }

        return array_reverse($posts);
    }

    /**	
     * Returns a user 
     * @return array users
     */
    public function getSinglePost($postID) {
        $sql = "SELECT users.username, posts.postTitle, posts.pk, posts.postText, posts.image
        		FROM ".self::$usersTable."
        		INNER JOIN ".self::$postsTable." ON users.pk = posts.ownerId
        		WHERE posts.pk = ".$postID.";";

        $statement = $this->mysqli->prepare($sql);
        if ($statement === false) {        	
            throw new \Exception("Preparation of $sql statement failed");
        }
        if ($statement->execute() === false) {
            throw new \Exception("Execution of $sql statement failed");
        }
        $result = $statement->get_result();
        $object = $result->fetch_array(MYSQLI_ASSOC);        
        $post = new \posts\model\Post($object["username"], 
                                      $object["pk"], 
                                      $object["postTitle"], 
                                      $object["postText"],
                                      $object["image"]);
        return $post;
    }

    /**
    * @param User user 
    * @throws Exception if something goes wrong.
    */
    public function addPost(\posts\model\Post $post, \posts\model\ImageModel $image) {

        var_dump($post);

    	$ownerId = $post->ID;
    	$title = $post->Title;
    	$text = $post->Text;
        $imageName = $image->imageName;
        $imagePath = $image->imagePath;
        $dbImage = $imagePath.$imageName;
    	$insert = true;

    	if ($ownerId == "" || $title == "") {
    		$insert = false;
    	}
        if ($insert === true) {         
			$sql = "INSERT INTO ".self::$postsTable."( postTitle, postText, ownerId, image ) VALUES(?, ?, ?, ?)";
			$statement = $this->mysqli->prepare($sql);
	        if ($statement === false) {
	            throw new \Exception("Preparation of $sql statement failed");
	        }
	        if ($statement->bind_param("ssis" ,$title, $text, $ownerId, $dbImage) === false) {
	            throw new \Exception("Binding of $sql failed");
	        }
	        if ($statement->execute() === false) {
	            throw new \Exception("Execution of $sql failed");
	        }
    	}
    }

	
	/**
    * From https://coursepress.lnu.se/kurs/webbutveckling-med-php/exempelsida/mysqli-och-dal/
    * Only run on new system
    */
    public function createPostTable() {        
        $sqlStmt = "CREATE TABLE `".self::$postsTable."` 
            (
                `pk` INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
                `postTitle` VARCHAR(100),
                `PostText` VARCHAR(255),
                `ownerId` int NOT NULL,
                `Date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                `image` VARCHAR(100),
                FOREIGN KEY (ownerId) REFERENCES users (pk) ON DELETE CASCADE ON UPDATE CASCADE
            )
            ENGINE = innoDB;";
       
      if ($this->mysqli->query($sqlStmt) === false) {
          throw new \Exception("'$sqlStmt' failed ");
      }
    }
}